#！encoding:utf-8
import xmltodict
import json
import time
from constants import config_obj,out,err,warn,debug
from collections import OrderedDict
from traceback import print_exc
import sys
reload(sys)
sys.setdefaultencoding('utf8') 


def show_china(s):
	try:
		print json.dumps(s, indent=2, ensure_ascii=False)
	except:
		print_exc()
		print s

def read_(path):
	with open(path,'r') as f:
		result = f.read()
		# print result
	return result


def for_(dict_):
	key_list = []
	key_dict = OrderedDict()
	for key, value in dict_.items():
		if isinstance(value,dict):
			# print key
			a,b = for_(value)
			key_list.extend(a)
			key_dict.update(b)
			print "#"*30
			print key_list
		elif isinstance(value,list):
			# print '*'*20
			list_keys = []
			list_dict = OrderedDict()
			for num,list_item in enumerate(value):
				num = str(int(num) + 1)
				if isinstance(list_item,dict):
					for list_key in list_item:
						new_list_key = list_key + '_' + num
						list_dict[new_list_key] = list_item[list_key]
						# print list_key
						list_keys.append(new_list_key)
			# print list_keys
			key_list.extend(list_keys)
			key_dict.update(list_dict)
			# print '*'*30
			# print key_list
		else:
			key_dict[key] = value
			key_list.append(key)
	print
	return key_list,key_dict


def xml_to_tup(data):
	try:
		item_info = xmltodict.parse(data)['DATA']
		show_china(item_info)
		print "*"*20
		# main_data = item_info['DATA']
		key_list,key_dict = for_(item_info)
		key_values = [key_dict[i] for i in key_dict]
		show_china(key_dict)
		print len(key_dict)
		print '_'*50
		print key_list
		print len(key_list)
		print '_'*50
		show_china(key_values)
		out("data parser is completed!")

	except:
		err("解析错误")
	return key_values, key_list



def do_update(s):
	time.sleep(5)
	print s
	out("done!")



if __name__ == '__main__':
	path = "./test.xml"
	xml_to_tup(path)
